

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=dark>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/my-blog/img/fluid.png">
  <link rel="icon" href="/my-blog/img/fluid.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="木舟">
  <meta name="keywords" content="python Vue Test 测试开发 自动化测试">
  
    <meta name="description" content="前言既然dom都可以支持事件监听，那么Vue同样可以支持。 并且，Vue中的监听，在实际开发过程中，会十分常用。 比如：  搜索功能，监听输入框的值，变动后直接搜索 监听弹窗关闭，关闭后，立即触发回调函数。  实际上，watch与computed很像，本质上都是监听组件属性来进行一些逻辑代码执行。 不通的是，computed大多数情况下，只能使用它来获取一些 即时 返回的数据，很难 支持一些复杂的">
<meta property="og:type" content="article">
<meta property="og:title" content="Vue--watch监听器">
<meta property="og:url" content="https://walker_kwu.gitee.io/my-blog/2022/11/13/notes/vue/watch/">
<meta property="og:site_name" content="My Blog">
<meta property="og:description" content="前言既然dom都可以支持事件监听，那么Vue同样可以支持。 并且，Vue中的监听，在实际开发过程中，会十分常用。 比如：  搜索功能，监听输入框的值，变动后直接搜索 监听弹窗关闭，关闭后，立即触发回调函数。  实际上，watch与computed很像，本质上都是监听组件属性来进行一些逻辑代码执行。 不通的是，computed大多数情况下，只能使用它来获取一些 即时 返回的数据，很难 支持一些复杂的">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2022-11-13T07:35:42.000Z">
<meta property="article:modified_time" content="2023-05-23T10:37:53.263Z">
<meta property="article:author" content="木舟">
<meta property="article:tag" content="测试开发">
<meta property="article:tag" content="测试平台">
<meta property="article:tag" content="javascript">
<meta property="article:tag" content="Vue">
<meta name="twitter:card" content="summary_large_image">
  
  
    <meta name="referrer" content="no-referrer-when-downgrade">
  
  
  <title>Vue--watch监听器 - My Blog</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/my-blog/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/my-blog/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/my-blog/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"walker_kwu.gitee.io","root":"/my-blog/","version":"1.9.2","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"left","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/my-blog/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/my-blog/js/utils.js" ></script>
  <script  src="/my-blog/js/color-schema.js" ></script>
  


  
<meta name="generator" content="Hexo 6.2.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/my-blog/">
      <strong>木舟</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/my-blog/img/default.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="Vue--watch监听器"></span>
          
        </div>

        
          
  <div class="mt-3">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-author" aria-hidden="true"></i>
        木舟
      </span>
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2022-11-13 15:35" pubdate>
          2022年11月13日 下午
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          6.2k 字
        
      </span>
    

    

    
    
      
        <span id="busuanzi_container_page_pv" style="display: none">
          <i class="iconfont icon-eye" aria-hidden="true"></i>
          <span id="busuanzi_value_page_pv"></span> 次
        </span>
        
      
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="padding-left: 2rem; margin-right: -1rem">
    <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">Vue--watch监听器</h1>
            
              <p class="note note-info">
                
                  
                    本文最后更新于：2023年5月23日 晚上
                  
                
              </p>
            
            
              <div class="markdown-body">
                
                <h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><p>既然dom都可以支持事件监听，那么Vue同样可以支持。</p>
<p>并且，Vue中的监听，在实际开发过程中，会十分常用。</p>
<p>比如：</p>
<ul>
<li>搜索功能，监听输入框的值，变动后直接搜索</li>
<li>监听弹窗关闭，关闭后，立即触发回调函数。</li>
</ul>
<p>实际上，watch与computed很像，本质上都是监听组件属性来进行一些逻辑代码执行。</p>
<p>不通的是，computed大多数情况下，只能使用它来获取一些 <strong>即时</strong> 返回的数据，<strong>很难</strong> 支持一些复杂的逻辑操作。</p>
<p>例如：</p>
<ul>
<li>更改Dom</li>
<li>异步获取接口</li>
<li>修改组件属性</li>
</ul>
<h1 id="基本示例"><a href="#基本示例" class="headerlink" title="基本示例"></a>基本示例</h1><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;template&gt;<br>	&lt;input type=&quot;text&quot; v-model=&quot;search&quot;&gt;<br><br>	&lt;div v-for=&quot;item in dataList&quot;&gt;&#123;&#123;item&#125;&#125;&lt;/div&gt;<br>&lt;/template&gt;<br><br>&lt;script setup&gt;<br>import &#123; ref, onBeforeMount, watch &#125; from &#x27;vue&#x27;;<br><br>const search = ref(&#x27;&#x27;)<br><br>const initDataList = [<br>	&#x27;John&#x27;,<br>	&#x27;Make&#x27;,<br>	&#x27;Kobe&#x27;,<br>	&#x27;James&#x27;<br>]<br><br>const dataList = ref([])<br><br>onBeforeMount(() =&gt; &#123;<br>	dataList.value = initDataList<br>&#125;)<br><br>watch(search, (newValue, oldValue)=&gt;&#123;<br>	dataList.value = initDataList.filter(item=&gt;item.indexOf(newValue) != -1)<br>&#125;)<br>&lt;/script&gt;<br></code></pre></td></tr></table></figure>

<h1 id="监听的数据源类型"><a href="#监听的数据源类型" class="headerlink" title="监听的数据源类型"></a>监听的数据源类型</h1><p>可以监听以下几种：</p>
<ul>
<li>ref</li>
<li>reactive</li>
<li>getter函数</li>
<li>多个数据源数组</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-keyword">const</span> x = <span class="hljs-title function_">ref</span>(<span class="hljs-number">0</span>)<br><span class="hljs-keyword">const</span> y = <span class="hljs-title function_">ref</span>(<span class="hljs-number">0</span>)<br><br><span class="hljs-comment">// 单个 ref</span><br><span class="hljs-title function_">watch</span>(x, <span class="hljs-function">(<span class="hljs-params">newX</span>) =&gt;</span> &#123;<br>  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`x is <span class="hljs-subst">$&#123;newX&#125;</span>`</span>)<br>&#125;)<br><br><span class="hljs-comment">// getter 函数</span><br><span class="hljs-title function_">watch</span>(<br>  <span class="hljs-function">() =&gt;</span> x.<span class="hljs-property">value</span> + y.<span class="hljs-property">value</span>,<br>  <span class="hljs-function">(<span class="hljs-params">sum</span>) =&gt;</span> &#123;<br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`sum of x + y is: <span class="hljs-subst">$&#123;sum&#125;</span>`</span>)<br>  &#125;<br>)<br><br><span class="hljs-comment">// 多个来源组成的数组</span><br><span class="hljs-title function_">watch</span>([x, <span class="hljs-function">() =&gt;</span> y.<span class="hljs-property">value</span>], <span class="hljs-function">(<span class="hljs-params">[newX, newY]</span>) =&gt;</span> &#123;<br>  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`x is <span class="hljs-subst">$&#123;newX&#125;</span> and y is <span class="hljs-subst">$&#123;newY&#125;</span>`</span>)<br>&#125;)<br><br></code></pre></td></tr></table></figure>

<p>注意，你不能直接侦听响应式对象的属性值，例如:</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><br><span class="hljs-keyword">const</span> obj = <span class="hljs-title function_">reactive</span>(&#123; <span class="hljs-attr">count</span>: <span class="hljs-number">0</span> &#125;)<br><br><span class="hljs-comment">// 错误，因为 watch() 得到的参数是一个 number</span><br><span class="hljs-title function_">watch</span>(obj.<span class="hljs-property">count</span>, <span class="hljs-function">(<span class="hljs-params">count</span>) =&gt;</span> &#123;<br>  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`count is: <span class="hljs-subst">$&#123;count&#125;</span>`</span>)<br>&#125;)<br></code></pre></td></tr></table></figure>

<p>如果需要监听reactive中的某个属性，应该使用 getter 函数</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-comment">// 提供一个 getter 函数</span><br><span class="hljs-title function_">watch</span>(<br>  <span class="hljs-function">() =&gt;</span> obj.<span class="hljs-property">count</span>,<br>  <span class="hljs-function">(<span class="hljs-params">count</span>) =&gt;</span> &#123;<br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`count is: <span class="hljs-subst">$&#123;count&#125;</span>`</span>)<br>  &#125;<br>)<br></code></pre></td></tr></table></figure>

<h1 id="深层侦听器"><a href="#深层侦听器" class="headerlink" title="深层侦听器"></a>深层侦听器</h1><p>直接给 watch() 传入一个响应式对象时，会隐式地创建一个深层侦听器——该回调函数在所有嵌套的变更时都会被触发。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;template&gt;<br>	&lt;button @click=&quot;obj.count++&quot;&gt;click&lt;/button&gt;<br>&lt;/template&gt;<br><br>&lt;script setup&gt;<br>import &#123; ref, onBeforeMount, watch, reactive &#125; from &#x27;vue&#x27;;<br><br>const obj = reactive(&#123; count: 0 &#125;)<br><br>watch(obj, (newValue, oldValue) =&gt; &#123;<br>  // 在嵌套的属性变更时触发<br>  // 注意：`newValue` 此处和 `oldValue` 是相等的<br>  // 因为它们是同一个对象！<br>  console.log(newValue);<br>  console.log(oldValue);<br>&#125;)<br>&lt;/script&gt;<br></code></pre></td></tr></table></figure>

<p>相比之下，一个返回响应式对象的 getter 函数，只有在返回不同的对象时，才会触发回调：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;template&gt;<br>	&lt;button @click=&quot;obj.count++&quot;&gt;click&lt;/button&gt;<br>&lt;/template&gt;<br><br>&lt;script setup&gt;<br>import &#123; ref, onBeforeMount, watch, reactive &#125; from &#x27;vue&#x27;;<br><br>const obj = reactive(&#123; count: 0 &#125;)<br><br>watch(()=&gt;obj.count, (newValue, oldValue) =&gt; &#123;<br>  // 在嵌套的属性变更时触发<br>  // 注意：`newValue` 此处和 `oldValue` 是相等的<br>  // 因为它们是同一个对象！<br>  console.log(newValue);<br>  console.log(oldValue);<br>&#125;)<br>&lt;/script&gt;<br></code></pre></td></tr></table></figure>

<h2 id="使用getter函数监听响应式对象"><a href="#使用getter函数监听响应式对象" class="headerlink" title="使用getter函数监听响应式对象"></a>使用getter函数监听响应式对象</h2><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;template&gt;<br>	&lt;button @click=&quot;obj.someObj.count++&quot;&gt;click&lt;/button&gt;<br>&lt;/template&gt;<br><br>&lt;script setup&gt;<br>import &#123; ref, onBeforeMount, watch, reactive &#125; from &#x27;vue&#x27;;<br><br>const obj = reactive(&#123;<br>	someObj: &#123;<br>		count: 0<br>	&#125;<br>&#125;)<br><br>watch(()=&gt;obj.someObj, (newValue, oldValue) =&gt; &#123;<br>  // 在嵌套的属性变更时触发<br>  // 注意：`newValue` 此处和 `oldValue` 是相等的<br>  // 因为它们是同一个对象！<br>  console.log(newValue);<br>  console.log(oldValue);<br>&#125;)<br>&lt;/script&gt;<br></code></pre></td></tr></table></figure>

<p>这个时候，点击按钮是不会触发 watch 的。</p>
<p>因为getter函数，只会当返回值变更时，才会触发。而修改 <strong>count</strong> 属性，实际上并不是修改 obj.someObj。</p>
<p>这个时候，我们可以手动指定 <code>&#123; deep: true &#125;</code>，使其变成 <strong>深层监听</strong></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;template&gt;<br>	&lt;button @click=&quot;obj.someObj.count++&quot;&gt;click&lt;/button&gt;<br>&lt;/template&gt;<br><br>&lt;script setup&gt;<br>import &#123; ref, onBeforeMount, watch, reactive &#125; from &#x27;vue&#x27;;<br><br>const obj = reactive(&#123;<br>	someObj: &#123;<br>		count: 0<br>	&#125;<br>&#125;)<br><br>watch(()=&gt;obj.someObj, (newValue, oldValue) =&gt; &#123;<br>  // 在嵌套的属性变更时触发<br>  // 注意：`newValue` 此处和 `oldValue` 是相等的<br>  // 因为它们是同一个对象！<br>    console.log(newValue);<br>    console.log(oldValue);<br>&#125;,<br>&#123;deep: true&#125;<br>)<br><br>&lt;/script&gt;<br></code></pre></td></tr></table></figure>

<p><strong>注意！！！</strong></p>
<blockquote>
<p>深度侦听需要遍历被侦听对象中的所有嵌套的属性，当用于大型数据结构时，开销很大。因此请只在必要时才使用它，并且要留意性能。<br>所以如果我们需要监听响应式对象中某个属性时，请直接指定属性路径，尽量避免 深层监听 的使用。</p>
</blockquote>
<h1 id="watchEffect"><a href="#watchEffect" class="headerlink" title="watchEffect"></a>watchEffect</h1><p>watch() 是懒执行的：仅当数据源变化时，才会执行回调。但在某些场景中，我们希望在创建侦听器时，立即执行一遍回调。</p>
<p>举例来说，我们想请求一些初始数据，然后在相关状态更改时重新请求数据。</p>
<p>借用章节 <strong>基本示例</strong> 中的例子：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;template&gt;<br>	&lt;input type=&quot;text&quot; v-model=&quot;search&quot;&gt;<br><br>	&lt;div v-for=&quot;item in dataList&quot;&gt;&#123;&#123;item&#125;&#125;&lt;/div&gt;<br>&lt;/template&gt;<br><br>&lt;script setup&gt;<br>import &#123; ref, onBeforeMount, watch &#125; from &#x27;vue&#x27;;<br><br>const search = ref(&#x27;&#x27;)<br><br>const initDataList = [<br>	&#x27;John&#x27;,<br>	&#x27;Make&#x27;,<br>	&#x27;Kobe&#x27;,<br>	&#x27;James&#x27;<br>]<br><br>const dataList = ref([])<br><br>onBeforeMount(() =&gt; &#123;<br>	dataList.value = initDataList<br>&#125;)<br><br>watch(search, (newValue, oldValue)=&gt;&#123;<br>	dataList.value = initDataList.filter(item=&gt;item.indexOf(newValue) != -1)<br>&#125;)<br>&lt;/script&gt;<br></code></pre></td></tr></table></figure>

<p>我们可以通过 <strong>watchEffect</strong> 改写：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-title function_">watchEffect</span>(<span class="hljs-function">()=&gt;</span>&#123;<br>	dataList.<span class="hljs-property">value</span> = initDataList.<span class="hljs-title function_">filter</span>(<span class="hljs-function"><span class="hljs-params">item</span>=&gt;</span>item.<span class="hljs-title function_">indexOf</span>(search.<span class="hljs-property">value</span>) != -<span class="hljs-number">1</span>)<br>&#125;)<br></code></pre></td></tr></table></figure>

<p>所以 <strong>watchEffect</strong> 并不需要我们手动指定监听什么属性，在 回调函数 中，用到了什么属性，<strong>watchEffect</strong> 会自动分析依赖属性，自动监听。</p>
<h1 id="watch-vs-watchEffect"><a href="#watch-vs-watchEffect" class="headerlink" title="watch vs watchEffect"></a>watch vs watchEffect</h1><p>watch 和 watchEffect 都能响应式地执行有副作用的回调。它们之间的主要区别是追踪响应式依赖的方式：</p>
<ul>
<li><p>watch 只追踪明确侦听的数据源。它不会追踪任何在回调中访问到的东西。另外，仅在数据源确实改变时才会触发回调。watch 会避免在发生副作用时追踪依赖，因此，我们能更加精确地控制回调函数的触发时机。</p>
</li>
<li><p>watchEffect，则会在副作用发生期间追踪依赖。它会在同步执行过程中，自动追踪所有能访问到的响应式属性。这更方便，而且代码往往更简洁，但有时其响应性依赖关系会不那么明确。</p>
</li>
</ul>
<h1 id="回调的触发时机"><a href="#回调的触发时机" class="headerlink" title="回调的触发时机"></a>回调的触发时机</h1><p>当你更改了响应式状态，它可能会同时触发 Vue 组件更新和侦听器回调。</p>
<p>默认情况下，用户创建的侦听器回调，都会在 Vue 组件更新之前被调用。这意味着你在侦听器回调中访问的 DOM 将是被 Vue 更新之前的状态。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;template&gt;<br>	&lt;button @click=&quot;show = true&quot;&gt;点我修改show =&gt; true&lt;/button&gt;<br>	&lt;div id=&quot;showDiv&quot; v-if=&quot;show&quot;&gt;我被看见了&lt;/div&gt;<br>&lt;/template&gt;<br><br>&lt;script setup&gt;<br>import &#123; ref, onBeforeMount, watchEffect, watch &#125; from &#x27;vue&#x27;;<br><br>const show = ref(false)<br><br>watch(show, (newValue)=&gt;&#123;<br>	const el = document.getElementById(&#x27;showDiv&#x27;)<br>	console.log(el); // null<br>&#125;)<br><br>&lt;/script&gt;<br></code></pre></td></tr></table></figure>

<p>如果想在侦听器回调中能访问被 Vue 更新之后的DOM，你需要指明 flush: ‘post’ 选项：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;template&gt;<br>	&lt;button @click=&quot;show = true&quot;&gt;点我修改show =&gt; true&lt;/button&gt;<br>	&lt;div id=&quot;showDiv&quot; v-if=&quot;show&quot;&gt;我被看见了&lt;/div&gt;<br>&lt;/template&gt;<br><br>&lt;script setup&gt;<br>import &#123; ref, onBeforeMount, watchEffect, watch &#125; from &#x27;vue&#x27;;<br><br>const show = ref(false)<br><br>watch(show, (newValue)=&gt;&#123;<br>	const el = document.getElementById(&#x27;showDiv&#x27;)<br>	console.log(el); // el<br>&#125;,<br>&#123;flush: &#x27;post&#x27;&#125;<br>)<br>&lt;/script&gt;<br></code></pre></td></tr></table></figure>

<p>后置刷新的 watchEffect() 有个更方便的别名 watchPostEffect()：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-keyword">import</span> &#123; watchPostEffect &#125; <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;vue&#x27;</span><br><br><span class="hljs-title function_">watchPostEffect</span>(<span class="hljs-function">() =&gt;</span> &#123;<br>  <span class="hljs-comment">/* 在 Vue 更新后执行 */</span><br>&#125;)<br></code></pre></td></tr></table></figure>
                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/my-blog/categories/%E6%B5%8B%E8%AF%95%E5%BC%80%E5%8F%91/" class="category-chain-item">测试开发</a>
  
  
    <span>></span>
    
  <a href="/my-blog/categories/%E6%B5%8B%E8%AF%95%E5%BC%80%E5%8F%91/Vue/" class="category-chain-item">Vue</a>
  
  

  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/my-blog/tags/%E6%B5%8B%E8%AF%95%E5%BC%80%E5%8F%91/">#测试开发</a>
      
        <a href="/my-blog/tags/%E6%B5%8B%E8%AF%95%E5%B9%B3%E5%8F%B0/">#测试平台</a>
      
        <a href="/my-blog/tags/javascript/">#javascript</a>
      
        <a href="/my-blog/tags/Vue/">#Vue</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>Vue--watch监听器</div>
      <div>https://walker_kwu.gitee.io/my-blog/2022/11/13/notes/vue/watch/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>木舟</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2022年11月13日</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>更新于</div>
          <div>2023年5月23日</div>
        </div>
      
      <div class="license-meta-item">
        <div>许可协议</div>
        <div>
          
            
            
              <a target="_blank" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">
              <span class="hint--top hint--rounded" aria-label="BY - 署名">
                <i class="iconfont icon-by"></i>
              </span>
              </a>
            
              <a target="_blank" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">
              <span class="hint--top hint--rounded" aria-label="NC - 非商业性使用">
                <i class="iconfont icon-nc"></i>
              </span>
              </a>
            
              <a target="_blank" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">
              <span class="hint--top hint--rounded" aria-label="SA - 相同方式共享">
                <i class="iconfont icon-sa"></i>
              </span>
              </a>
            
          
        </div>
      </div>
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/my-blog/2022/11/16/python/basic/base/" title="Python基础">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">Python基础</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/my-blog/2022/11/13/notes/vue/lifecycle/" title="生命周期">
                        <span class="hidden-mobile">生命周期</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <span>By 木舟</span> <i class="iconfont icon-love"></i> 
    </div>
  
  
    <div class="statistics">
  
  

  
    
      <span id="busuanzi_container_site_pv" style="display: none">
        总访问量 
        <span id="busuanzi_value_site_pv"></span>
         次
      </span>
    
    
      <span id="busuanzi_container_site_uv" style="display: none">
        总访客数 
        <span id="busuanzi_value_site_uv"></span>
         人
      </span>
    
    
  
</div>

  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/my-blog/js/events.js" ></script>
<script  src="/my-blog/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/my-blog/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      headingSelector : CONFIG.toc.headingSelector || 'h1,h2,h3,h4,h5,h6',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      collapseDepth   : CONFIG.toc.collapseDepth || 0,
      scrollSmooth    : true,
      headingsOffset  : -boardTop
    });
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.10/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/my-blog/js/local-search.js" ></script>

  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/my-blog/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
